/**********************************************************************************
// Vector Source
// 
// Creation:	19 Set 2008
// Updated:		23 Ago 2011
// Compiler:	Visual Studio 2010
//
// Notes:		Define vector arithmetics
//
**********************************************************************************/

#include "Vector.h"

const double Vector2::PI = 3.1415926535;

/**********************************************************************************/

Vector2::Vector2()
{
	angle     = 0;
	magnitude = 0;
}

/**********************************************************************************/

Vector2::Vector2(float ang, float mag)
{
	angle     = ang;
	magnitude = mag;
}

/**********************************************************************************/

void Vector2::SetVector(float ang, float mag)
{
	angle     = ang;
	magnitude = mag;
}

/**********************************************************************************/

void Vector2::Rotate(float theta)
{
	angle -= theta;

	// keep angle from 0 to 359 degrees
	while (!(angle >= 0 && angle < 360))
	{
		if (angle >= 360)
			angle -= 360.0f;
		else
			angle += 360.0f;
	}
}

/**********************************************************************************/

void Vector2::Add(const Vector2 &v)
{
	float rx, ry;

	rx = GetX() + v.GetX();
	ry = GetY() + v.GetY();

	magnitude = sqrt(pow(rx,2) + pow(ry,2));
	
	// correct the result from atan function
	if (rx > 0) 
	{
		// 1st Quadrant
		if (ry >= 0)
		{
			// find angle in radians
			angle = atan(ry/rx);
			// convert radians to degrees
			angle = float((180.0 * angle) / PI);
		}
		// 4th Quadrant
		else // (ry < 0)
		{
			// find angle in radians
			angle = atan(ry/rx);
			// convert radians to degrees
			angle = float((180.0 * angle) / PI) + 360.0f;
		}
	}
	// 2nd and 3rd Quadrant
	else if (rx < 0)
	{
		// find angle in radians
		angle = atan(ry/rx);
		// convert radians to degrees
		angle = float((180.0 * angle) / PI) + 180.0f;
	}
	else // (rx == 0)
	{
		if (ry > 0)
			angle = 90.0f;
		else if (ry < 0)
			angle = 270.0f;
		else // (ry == 0)
			angle = v.Ang();
	}
}

/**********************************************************************************/